"use client"

import { useState, useRef, useCallback, useEffect } from "react"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  TrendingUp,
  TrendingDown,
  Activity,
  Target,
  BarChart3,
  AlertTriangle,
  Filter,
  Loader2,
} from "lucide-react"
import { SignalTradeDetail } from "@/lib/api/tracking"
import { cn } from "@/lib/utils"

/**
 * 格式化百分比
 */
const formatPercent = (value: number, showSign = true, decimals = 2) => {
  const sign = showSign && value > 0 ? '+' : ''
  return `${sign}${value.toFixed(decimals)}%`
}

/**
 * 交易明细对话框组件属性
 */
interface SignalTradesDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  signalName: string
  tradeDetails: SignalTradeDetail[]
  isLoading: boolean
  // 分页信息
  hasMore: boolean
  currentPage: number
  totalPages: number
  totalRecords: number
  // 加载更多回调
  onLoadMore: () => void
  isLoadingMore: boolean
}

/**
 * 信号交易明细对话框组件
 */
export function SignalTradesDialog({
  open,
  onOpenChange,
  signalName,
  tradeDetails,
  isLoading,
  hasMore,
  currentPage,
  totalPages,
  totalRecords,
  onLoadMore,
  isLoadingMore,
}: SignalTradesDialogProps) {
  const [filterType, setFilterType] = useState<'all' | 'win' | 'loss'>('all')
  const [sortBy, setSortBy] = useState<'date' | 'return' | 'holding'>('date')
  const scrollContainerRef = useRef<HTMLDivElement>(null)

  // 滚动到底部加载更多
  const handleScroll = useCallback(() => {
    const container = scrollContainerRef.current
    if (!container || isLoadingMore || !hasMore) return

    const { scrollTop, scrollHeight, clientHeight } = container
    // 距离底部100px时触发加载
    if (scrollHeight - scrollTop - clientHeight < 100) {
      onLoadMore()
    }
  }, [hasMore, isLoadingMore, onLoadMore])

  // 监听滚动事件
  useEffect(() => {
    const container = scrollContainerRef.current
    if (!container) return

    container.addEventListener('scroll', handleScroll)
    return () => container.removeEventListener('scroll', handleScroll)
  }, [handleScroll])

  // 计算统计数据
  const stats = {
    total: tradeDetails.length,
    winCount: tradeDetails.filter(t => t.isWin).length,
    lossCount: tradeDetails.filter(t => !t.isWin).length,
    winRate: tradeDetails.length > 0 
      ? (tradeDetails.filter(t => t.isWin).length / tradeDetails.length) * 100 
      : 0,
    avgReturn: tradeDetails.length > 0
      ? tradeDetails.reduce((sum, t) => sum + t.returnRate, 0) / tradeDetails.length
      : 0,
  }

  // 筛选和排序数据
  const filteredAndSortedTrades = tradeDetails
    .filter(trade => {
      if (filterType === 'win') return trade.isWin
      if (filterType === 'loss') return !trade.isWin
      return true
    })
    .sort((a, b) => {
      switch (sortBy) {
        case 'date':
          return new Date(b.buyDate).getTime() - new Date(a.buyDate).getTime()
        case 'return':
          return b.returnRate - a.returnRate
        case 'holding':
          return b.holdingDays - a.holdingDays
        default:
          return 0
      }
    })

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="w-[96vw] max-w-none max-h-[96vh] overflow-hidden flex flex-col p-0">
        {/* 对话框头部 */}
        <div className="px-6 py-4 border-b bg-gradient-to-r from-accent/5 to-transparent">
          <DialogHeader>
            <div className="flex items-center justify-between">
              <div>
                <DialogTitle className="text-2xl font-bold flex items-center gap-3">
                  <div className="w-1 h-8 bg-accent rounded-full" />
                  {signalName}
                </DialogTitle>
                <DialogDescription className="mt-2 text-base">
                  信号交易明细与绩效分析
                </DialogDescription>
              </div>
              {totalRecords > 0 && (
                <Badge variant="outline" className="text-base px-4 py-2 font-mono">
                  共 {totalRecords} 笔交易 (已加载 {stats.total})
                </Badge>
              )}
            </div>
          </DialogHeader>
        </div>

        {/* 对话框内容 */}
        <div ref={scrollContainerRef} className="flex-1 overflow-y-auto px-6 py-4">
          {isLoading ? (
            <div className="space-y-4">
              <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                {Array.from({ length: 5 }).map((_, i) => (
                  <Skeleton key={i} className="h-24 w-full rounded-lg" />
                ))}
              </div>
              <Skeleton className="h-12 w-full rounded-lg" />
              <div className="space-y-2">
                {Array.from({ length: 6 }).map((_, i) => (
                  <Skeleton key={i} className="h-16 w-full rounded-lg" />
                ))}
              </div>
            </div>
          ) : stats.total > 0 ? (
            <div className="space-y-6">
              {/* 统计汇总卡片 */}
              <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                <Card className="border-l-4 border-l-accent bg-gradient-to-br from-accent/5 to-transparent hover:shadow-lg transition-all duration-300">
                  <CardContent className="p-4">
                    <div className="flex items-center justify-between mb-2">
                      <p className="text-xs font-medium text-muted-foreground">总交易次数</p>
                      <BarChart3 className="w-4 h-4 text-accent" />
                    </div>
                    <p className="text-2xl font-bold font-mono">{stats.total}</p>
                    <p className="text-xs text-muted-foreground mt-1">笔交易记录</p>
                  </CardContent>
                </Card>
                
                <Card className="border-l-4 border-l-success bg-gradient-to-br from-success/5 to-transparent hover:shadow-lg transition-all duration-300">
                  <CardContent className="p-4">
                    <div className="flex items-center justify-between mb-2">
                      <p className="text-xs font-medium text-muted-foreground">盈利交易</p>
                      <TrendingUp className="w-4 h-4 text-success" />
                    </div>
                    <p className="text-2xl font-bold font-mono text-success">
                      {stats.winCount}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      占比 {((stats.winCount / stats.total) * 100).toFixed(1)}%
                    </p>
                  </CardContent>
                </Card>
                
                <Card className="border-l-4 border-l-destructive bg-gradient-to-br from-destructive/5 to-transparent hover:shadow-lg transition-all duration-300">
                  <CardContent className="p-4">
                    <div className="flex items-center justify-between mb-2">
                      <p className="text-xs font-medium text-muted-foreground">亏损交易</p>
                      <TrendingDown className="w-4 h-4 text-destructive" />
                    </div>
                    <p className="text-2xl font-bold font-mono text-destructive">
                      {stats.lossCount}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      占比 {((stats.lossCount / stats.total) * 100).toFixed(1)}%
                    </p>
                  </CardContent>
                </Card>
                
                <Card className="border-l-4 border-l-primary bg-gradient-to-br from-primary/5 to-transparent hover:shadow-lg transition-all duration-300">
                  <CardContent className="p-4">
                    <div className="flex items-center justify-between mb-2">
                      <p className="text-xs font-medium text-muted-foreground">交易胜率</p>
                      <Target className="w-4 h-4 text-primary" />
                    </div>
                    <p className="text-2xl font-bold font-mono">
                      {formatPercent(stats.winRate, false, 1)}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      {stats.winCount}胜/{stats.lossCount}负
                    </p>
                  </CardContent>
                </Card>
                
                <Card className="border-l-4 border-l-purple-500 bg-gradient-to-br from-purple-500/5 to-transparent hover:shadow-lg transition-all duration-300">
                  <CardContent className="p-4">
                    <div className="flex items-center justify-between mb-2">
                      <p className="text-xs font-medium text-muted-foreground">平均收益率</p>
                      <Activity className="w-4 h-4 text-purple-500" />
                    </div>
                    <p className={cn(
                      "text-2xl font-bold font-mono",
                      stats.avgReturn >= 0 ? "text-success" : "text-destructive"
                    )}>
                      {formatPercent(stats.avgReturn)}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      所有交易平均
                    </p>
                  </CardContent>
                </Card>
              </div>

              {/* 筛选和排序控制栏 */}
              <Card className="bg-muted/30">
                <CardContent className="p-4">
                  <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
                    <div className="flex items-center gap-2">
                      <Filter className="w-4 h-4 text-muted-foreground" />
                      <span className="text-sm font-medium">数据筛选</span>
                    </div>
                    
                    <div className="flex flex-wrap items-center gap-3">
                      {/* 盈亏筛选 */}
                      <div className="flex items-center gap-2">
                        <Button
                          variant={filterType === 'all' ? 'default' : 'outline'}
                          size="sm"
                          onClick={() => setFilterType('all')}
                          className="h-8 text-xs"
                        >
                          全部 ({stats.total})
                        </Button>
                        <Button
                          variant={filterType === 'win' ? 'default' : 'outline'}
                          size="sm"
                          onClick={() => setFilterType('win')}
                          className="h-8 text-xs"
                        >
                          <TrendingUp className="w-3 h-3 mr-1" />
                          盈利 ({stats.winCount})
                        </Button>
                        <Button
                          variant={filterType === 'loss' ? 'default' : 'outline'}
                          size="sm"
                          onClick={() => setFilterType('loss')}
                          className="h-8 text-xs"
                        >
                          <TrendingDown className="w-3 h-3 mr-1" />
                          亏损 ({stats.lossCount})
                        </Button>
                      </div>

                      <div className="w-px h-6 bg-border" />

                      {/* 排序方式 */}
                      <Select value={sortBy} onValueChange={(value: any) => setSortBy(value)}>
                        <SelectTrigger className="w-[140px] h-8 text-xs">
                          <SelectValue placeholder="排序方式" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="date">按日期排序</SelectItem>
                          <SelectItem value="return">按收益率排序</SelectItem>
                          <SelectItem value="holding">按持仓天数</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 交易明细表格 */}
              <Card>
                <div className="rounded-lg overflow-hidden border">
                  <Table>
                    <TableHeader>
                      <TableRow className="bg-muted/50 hover:bg-muted/50">
                        <TableHead className="w-16 font-semibold">#</TableHead>
                        <TableHead className="font-semibold">股票信息</TableHead>
                        <TableHead className="font-semibold">买入信息</TableHead>
                        <TableHead className="font-semibold">卖出信息</TableHead>
                        <TableHead className="text-center font-semibold">持仓</TableHead>
                        <TableHead className="text-right font-semibold">收益率</TableHead>
                        <TableHead className="text-center font-semibold">状态</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredAndSortedTrades.map((trade, index) => (
                        <TableRow 
                          key={index} 
                          className="hover:bg-accent/5 transition-colors border-b last:border-0"
                        >
                          <TableCell className="font-medium text-muted-foreground">
                            {index + 1}
                          </TableCell>
                          <TableCell>
                            <div className="space-y-1">
                              <p className="font-mono text-sm font-semibold">{trade.stockCode}</p>
                              <p className="text-xs text-muted-foreground">{trade.stockName}</p>
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="space-y-1">
                              <p className="text-xs text-muted-foreground">{trade.buyDate}</p>
                              <p className="font-mono text-sm font-medium">¥{trade.buyPrice.toFixed(2)}</p>
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="space-y-1">
                              <p className="text-xs text-muted-foreground">{trade.sellDate}</p>
                              {trade.sellDate === '持仓中' ? (
                                <Badge variant="outline" className="text-xs">
                                  持仓中
                                </Badge>
                              ) : (
                                <p className="font-mono text-sm font-medium">¥{trade.sellPrice.toFixed(2)}</p>
                              )}
                            </div>
                          </TableCell>
                          <TableCell className="text-center">
                            <Badge variant="outline" className="font-mono">
                              {trade.holdingDays}天
                            </Badge>
                          </TableCell>
                          <TableCell className="text-right">
                            <div className="flex flex-col items-end gap-1">
                              <div className="flex items-center gap-2">
                                {trade.isWin ? (
                                  <TrendingUp className="w-4 h-4 text-success" />
                                ) : (
                                  <TrendingDown className="w-4 h-4 text-destructive" />
                                )}
                                <span className={cn(
                                  "font-bold font-mono text-base",
                                  trade.isWin ? "text-success" : "text-destructive"
                                )}>
                                  {formatPercent(trade.returnRate)}
                                </span>
                              </div>
                              {trade.sellDate === '持仓中' && (
                                <span className="text-xs text-muted-foreground">
                                  (浮动收益)
                                </span>
                              )}
                            </div>
                          </TableCell>
                          <TableCell className="text-center">
                            {trade.sellDate === '持仓中' ? (
                              <Badge 
                                variant="outline"
                                className="font-medium bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/30"
                              >
                                ⏱ 持仓中
                              </Badge>
                            ) : (
                              <Badge 
                                variant={trade.isWin ? "default" : "destructive"}
                                className={cn(
                                  "font-medium",
                                  trade.isWin 
                                    ? "bg-success/20 text-success hover:bg-success/30 border-success/30" 
                                    : "bg-destructive/20 text-destructive hover:bg-destructive/30 border-destructive/30"
                                )}
                              >
                                {trade.isWin ? "✓ 盈利" : "✗ 亏损"}
                              </Badge>
                            )}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </Card>

              {/* 加载更多指示器 */}
              {isLoadingMore && (
                <div className="flex items-center justify-center py-6">
                  <Loader2 className="w-6 h-6 animate-spin text-accent mr-2" />
                  <span className="text-sm text-muted-foreground">加载中...</span>
                </div>
              )}

              {/* 已加载全部数据提示 */}
              {!hasMore && stats.total > 0 && (
                <div className="flex items-center justify-center py-4">
                  <p className="text-sm text-muted-foreground">
                    已加载全部 {totalRecords} 条记录
                  </p>
                </div>
              )}
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center py-16">
              <div className="w-20 h-20 rounded-full bg-muted/30 flex items-center justify-center mb-4">
                <AlertTriangle className="w-10 h-10 text-muted-foreground" />
              </div>
              <p className="text-xl font-semibold mb-2">暂无交易记录</p>
              <p className="text-sm text-muted-foreground">
                该信号在选定时间范围内暂无交易记录
              </p>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  )
}

